import socket
import ssl
from tkinter import *

''''
    
'''


def findall_in_html(html, startPart, endPart):
    all_strings =[]
    start = html.find(startPart)+len(startPart)
    end = html.find(endPart, start)
    string = html[start:end]
    while html.find('</html>') > start > html.find('<html'):
        all_strings.append(string)
        start = html.find(startPart,start) + len(startPart)
        end = html.find(endPart, start)
        string = html[start:end]
    return all_strings


def movie_name(html):
    name = findall_in_html(html, '<span class="title">', '</span>')
    for i in name:
        if 'bsp;' in i:
            name.remove(i)
    return name


def movie_score(html):
    score = findall_in_html(html, '<span class="rating_num" property="v:average">', '</span>')
    return score


def movie_infq(html):
    infq = findall_in_html(html, '<span class="inq">', '</span>')
    return infq


def num_comment(html):
    temp = findall_in_html(html,' <div class="star">', '</div>')
    num = []
    for item in temp:
        start = item.find('<span>')+len('<span>')
        end = item.find('</span>', start)
        n = item[start:end]
        num.append(n)
    return num


def htmls_from_douban():
    html = []
    url = "https://movie.douban.com/top250?start={}&filter="
    for index in range(0, 250, 25):
        r = get(url.format(index))
        html.append(r)
    return html


def movie_data_from_html(htmls):
    movie =[]
    score =[]
    infq =[]
    number =[]
    for h in htmls:
        m = movie_name(h)
        s = movie_score(h)
        i = movie_infq(h)
        n = num_comment(h)
        movie.extend(m)
        score.extend(s)
        infq.extend(i)
        number.extend(n)
    data = zip(movie, score, infq, number)
    return data




# 分析网址
def get(url):
    # 获取到协议名
    protocol = url.split('://')[0]
    # 获取到协议名后面的主机名和路径名
    u = url.split('://')[1]
    # 以‘/’切片
    i = u.find('/')
    # 获取到主机名
    host = u[:i]
    # 获取到路径名
    path = u[i:]
    if protocol == 'https':
        s = ssl.wrap_socket(socket.socket())
        # 默认端口443
        port = 443
    else:
        s = socket.socket()
        port = 80
    # 实现连接
    s.connect((host, port))
    request = 'GET {} HTTP/1.1\r\nhost:{}\r\n\r\n'.format(path, host)
    s.send(request.encode(encoding='utf-8'))

    response = b''
    while True:
        r = s.recv(1024)
        response += r
        if len(r) < 1024:
            break
    response = response.decode(encoding='utf-8')

    return response


def movie_log(*args, **kwargs):
    with open('movie.txt', 'a', encoding='utf-8') as f:
        print(*args, file = f, **kwargs)



def main():
    htmls = htmls_from_douban()
    movie_data = movie_data_from_html(htmls)
    counter = 0
    for item in movie_data:
        counter = counter + 1
        movie_log('No.'+str(counter))
        movie_log('电影名:', item[0])
        movie_log('评分:', item[1])
        movie_log('引用语:', item[2])
        movie_log('评价人数:', item[3])

main()
# 定义界面



count = 0

# 获取资料
def get_info():
    datas=[]
    data =[]
    i = 0
    with open('movie.txt','r',encoding='utf-8') as f:
        while True:
            i = i + 1
            tmp = f.readline()
            if tmp == '':
                break
            data.append(tmp)
        for i in range(245):
            datas.append(data[i*5:(i+1)*5])
    return datas


count = 0
datas = get_info()

def all_fun():
    global count
    ch = ''
    global datas
    for i in range(len(datas[0])):
        ch += str(datas[count][i])+'\n'
    e.set(ch)


def up_fun():
    global count
    if count == 0:
        count = len(datas)-1
    else:
        count -= 1
    all_fun()

def down_fun():
    global count
    if count == len(datas)-1:
        count = 0
    else:
        count += 1
    all_fun()



root = Tk()
root.title('豆瓣前245')
root.geometry('450x450')
e = StringVar()
result = Label(root, textvariable=e,font ='宋体-20',bg='white',width=60,height=20)

ch = ''
for i in range(5):
    ch += str(datas[0][i])+'\n'
    e.set(ch)


result.pack(side='top')
up = Button(root,text = '上一条', font = 'Times-20',command = up_fun,width = 5,height=1)
down = Button(root,text = '下一条', font = 'Times-20',command = down_fun,width = 5,height=1)
up.pack(side='left',padx=80)
down.pack(side='right',padx=80)
root.mainloop()